package com.zoshine.zzg.controller;

import com.zoshine.zzg.annotation.DisableLoginCheck;
import com.zoshine.zzg.config.ProjectConfig;
import com.zoshine.zzg.constant.Session;
import com.zoshine.zzg.pojo.PrisonerInfo;
import com.zoshine.zzg.service.InitService;
import com.zoshine.zzg.service.PrisonerInfoService;
import org.patchca.filter.predefined.*;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;
import java.util.Random;





/**
 * 主控制器，主要处理页面请求
 *
 * @author 贾俊峰
 * @time 2017/6/20 09:44
 */
@Controller
public class MainController extends BaseController {
    private ProjectConfig projectConfig;
    private PrisonerInfoService prisonerInfoService;
    private InitService initService;
    @Autowired
    public void setProjectConfig(ProjectConfig projectConfig) {
        this.projectConfig = projectConfig;
    }
    @Autowired
    public void setPrisonerInfoService(PrisonerInfoService prisonerInfoService) {
        this.prisonerInfoService = prisonerInfoService;
    }
    @Autowired
    public void setInitService(InitService initService) {
        this.initService = initService;
    }

    /**
     * 初始化页
     */
    @RequestMapping("init.html")
    @DisableLoginCheck
    public String init() {
        boolean canInit = initService.initAble();
        if (canInit) {
            return "init";
        }
        return "error/403";
    }

    /**
     * 索引页
     */
    @RequestMapping({"/", "index.html"})
    public ModelAndView index(Model model) {
        model.addAttribute("environment", projectConfig.getEnvironment());
        model.addAttribute("loginName",getLoginUserName());
        if (Objects.equals(projectConfig.getEnvironment(), "bank")) {
            return new ModelAndView("index");
        }
        return new ModelAndView("index");
    }

    /**
     * 首页
     */
    @RequestMapping("home.html")
    public String home() {
        return "home";
    }

    /**
     * 登录页
     */
    @DisableLoginCheck
    @RequestMapping("login.html")
    public String login() {
        return "login";
    }

    /**
     * 登出页
     */
    @RequestMapping("logout.html")
    public void logout() throws IOException {
        Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            session.removeAttribute(name);
        }
        response.sendRedirect("login.html");
    }
    /**
     * 修改密码页面
     */
    @RequestMapping("password")
    public ModelAndView password() {
        ModelAndView view = new ModelAndView("password");
        view.addObject("loginName",getLoginUserName());
        return view;
    }
    /**
     * 犯人点单页
     */
    @RequestMapping("order/addCommodity.html")
    @DisableLoginCheck
    public String prisonerOrder(Long prisonerId) {
        PrisonerInfo prisonerInfo = prisonerInfoService.get(prisonerId);
        if (prisonerInfo == null) {
            return "error/403";
        }
        session.setAttribute(Session.PRISONER_INFO, prisonerInfo);
        return "order/addCommodity";
    }

    @RequestMapping("/{path}/{name}.html")
    public String getHtml(@PathVariable String path, @PathVariable String name) {
//        File file1 = new File("src/main/resources/static/html/" + path +"/" + name + ".html");
//        File file2 = new File("zzg-inner/src/main/resources/static/html/" + path +"/" + name + ".html");
//        if (file1.exists()) {
//            return path + "/" + name;
//        } else if (file2.exists()){
//            return path + "/" + name;
//        }
        return path + "/" + name;
//        return "error/404";
    }


    @RequestMapping("/{path}/{path1}/{name}.html")
    public String getHtml(@PathVariable String path, @PathVariable String path1, @PathVariable String name) {
//        File file = new File("zzg-inner/src/main/resources/static/html/" + path +"/" + name + ".html");
//        if (file.exists()) {
//        } else {
//            return "error-404";
//        }
    	return path + "/"+path1+"/" + name;
    }


    //=========================验证码相关=================
    private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
    private static Random random = new Random();

    static {
        cs.setColorFactory(x -> {
            int[] c = new int[3];
            int i = random.nextInt(c.length);
            for (int fi = 0; fi < c.length; fi++) {
                if (fi == i) {
                    c[fi] = random.nextInt(71);
                } else {
                    c[fi] = random.nextInt(256);
                }
            }
            return new Color(c[0], c[1], c[2]);
        });
        RandomWordFactory wf = new RandomWordFactory();
        wf.setCharacters("abcdefghijkmnpqrstuvwxyzABCEFGHIJKLMNPQRSTUVWXYZ");
        wf.setMaxLength(4);
        wf.setMinLength(4);
        cs.setWordFactory(wf);
    }

    /**
     * 获取验证码
     */
    @DisableLoginCheck
    @RequestMapping("/patchca.img")
    public void patchca(HttpServletResponse response, HttpSession session) throws IOException {
        switch (random.nextInt(5)) {
            case 0:
                cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
                break;
            case 1:
                cs.setFilterFactory(new MarbleRippleFilterFactory());
                break;
            case 2:
                cs.setFilterFactory(new DoubleRippleFilterFactory());
                break;
            case 3:
                cs.setFilterFactory(new WobbleRippleFilterFactory());
                break;
            case 4:
                cs.setFilterFactory(new DiffuseRippleFilterFactory());
                break;
        }
        setResponseHeaders(response);
        String patchca = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
        session.setAttribute(Session.LOGIN_PATCHCA, patchca);
    }

    private void setResponseHeaders(HttpServletResponse response) {
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        long time = System.currentTimeMillis();
        response.setDateHeader("Last-Modified", time);
        response.setDateHeader("Date", time);
        response.setDateHeader("Expires", time);
    }
}
